﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NBOW
{
    public partial class EnterBug : Form
    {
        public EnterBug()
        {
            InitializeComponent();
        }

        #region Members

        public string path = string.Empty; // get path to save file
        public string pub_str_FieldChecked = string.Empty; // get Field checked
        double threshold = 0.9;  // normalized document length
        ConnectDB connect = new ConnectDB();
        
        Common com = new Common();
        Calculator cal = new Calculator();
        Dictionary<string, double> dicbug_duplicate;
        Dictionary<string, double> dictemp_duplicate;

        #endregion

        #region Event Handlers

        private void btnExportData_Click(object sender, EventArgs e)
        {
            openFilePath.ShowDialog();
            string File = openFilePath.FileName;
            if (string.IsNullOrEmpty(File))
                return;
            txtPath.Text = File;
            if (txtPath.Text != string.Empty)
            {
                DataTable dtBuild = connect.getDataFromXLS(txtPath.Text);
                ShowCboRow(dtBuild);
                if (dtBuild != null)
                {
                    foreach (DataColumn item in dtBuild.Columns)
                    {
                        bool bl_check = false;
                        foreach (Control ct in gbInfoBug.Controls)
                        {
                            if (ct.GetType().Name == "TextBox")
                            {
                                if (ct.Name.ToString() == item.ToString())
                                {
                                    ct.Text = item.Table.Rows[0][item.ToString()].ToString();
                                    bl_check = true;
                                }
                            }
                            if (bl_check == true)
                                break;
                        }
                    }
                }
            }
        }

        private void EnterBug_Load(object sender, EventArgs e)
        {
            BuildControls();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            DataTable dtBuild = connect.getDataFromXLS(path);
            Dictionary<string, double> listResult = new Dictionary<string, double>();
            List<string> listFieldChecked = new List<string>();// contains field chose.

            if (dtBuild.Rows.Count > 0)
            {
                listFieldChecked = GetFieldCheck(dtBuild);//get Field checked
                string str_BugCurrent = string.Empty;// Bug current

                foreach (Control item in gbInfoBug.Controls)
                {
                    if (item.GetType().Name == "TextBox")
                    {
                        foreach (string s in listFieldChecked)
                        {
                            if (s == item.Name)
                                str_BugCurrent += item.Text + " ";
                        }
                    }
                }
                //Search 
                if (str_BugCurrent != string.Empty)
                {
                    listResult = cal.Score(str_BugCurrent,dtBuild,listFieldChecked);
                }
                ShowResultSearch(listResult, gvSearch);
            }
        }

        private void btnDuplicate_Click(object sender, EventArgs e)
        {
            DataTable dtBuild = connect.getDataFromXLS(path);
            
            List<string> listFieldChecked = new List<string>();// contains field chose.

            if (dtBuild.Rows.Count > 0)
            {
                listFieldChecked = GetFieldCheck(dtBuild);//get Field checked
                string str_BugCurrent = string.Empty;// Bug current
                foreach (Control item in gbInfoBug.Controls)
                {
                    if (item.GetType().Name == "TextBox")
                    {
                        foreach (string s in listFieldChecked)
                        {
                            if (s == item.Name)
                                str_BugCurrent += item.Text + " ";
                        }
                    }
                }
                //Find duplicate bug bt VSM
                if (str_BugCurrent != string.Empty)
                {
                    CheckDulicate(str_BugCurrent, dtBuild, listFieldChecked);
                    ShowResultSearch(dicbug_duplicate, gvDuplicate);
                    ShowResultSearch(dictemp_duplicate, gvTemp);
                }
                
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cboRow_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtPath.Text != string.Empty)
            {
                DataTable dtBuild = connect.getDataFromXLS(txtPath.Text);
                if (dtBuild != null)
                {
                    foreach (DataColumn item in dtBuild.Columns)
                    {
                        bool bl_check = false;
                        foreach (Control ct in gbInfoBug.Controls)
                        {
                            if (ct.GetType().Name == "TextBox")
                            {
                                if (ct.Name.ToString() == item.ToString())
                                {
                                    ct.Text = item.Table.Rows[cboRow.SelectedIndex][item.ToString()].ToString();
                                    bl_check = true;
                                }
                            }
                            if (bl_check == true)
                                break;
                        }
                    }
                }
            }
        }

        #endregion

        #region Functions

        private void ShowResultSearch(Dictionary<string, double> listResult, DataGridView gv)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Bug Report");

            List<double> value = new List<double>();
            foreach (string s in listResult.Keys)
            {
                value.Add(double.Parse(listResult[s].ToString()));
            }
            value.Sort();
            value.Reverse();
            List<KeyValuePair<string, double>> lstValue = new List<KeyValuePair<string, double>>(listResult);
            lstValue.Sort(
                delegate(KeyValuePair<string, double> firstPair,
                KeyValuePair<string, double> nextPair)
                {
                    return firstPair.Value.CompareTo(nextPair.Value);
                }
            );
            lstValue.Reverse();

            //Dictionary<int, string> dicValue = new Dictionary<int, string>();

            //for (int k = 0; k < lstValue.Count; k++)
            //{
            //    List<string> lstTemp = new List<string>();
            //    lstTemp.AddRange(lstValue[k].Key[k].ToString().Split(' '));
            //    dicValue.Add(lstTemp[0].ToString(),);
            //}
            #region Create Datatable
            // Create new DataTable and DataSource objects.
            DataTable table = new DataTable();

            // Declare DataColumn and DataRow variables.
            DataColumn column;
            DataRow row;
            DataView view;

            // Create new DataColumn, set DataType, ColumnName and add to DataTable.
            //column = new DataColumn();
            //column.DataType = System.Type.GetType("System.Int32");
            //column.ColumnName = "ID";
            //table.Columns.Add(column);

            // Create second column.
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "Bug Report";
            table.Columns.Add(column);

            
            column = new DataColumn();
            column.DataType = Type.GetType("System.Double");
            column.ColumnName = "Weight";
            table.Columns.Add(column);

            // Create new DataRow objects and add to DataTable. 
            for (int i = 0; i < lstValue.Count; i++)
            {
                row = table.NewRow();
                row["Bug Report"] = lstValue[i].Key.ToString();
                row["Weight"] = lstValue[i].Value.ToString();
                table.Rows.Add(row);

            }
            
            // Create a DataView using the DataTable.
            view = new DataView(table);
           
            // Show gridview
            gv.DataSource = view;
            gv.AutoResizeColumn(0);
            #endregion
          
        }

        //Build control Field
        private void BuildControls()
        {
            try
            {
                DataTable dtBuild = connect.getDataFromXLS(path);
                int i = 20;
                foreach (DataColumn item in dtBuild.Columns)
                {
                    var lbl = new Label();
                    lbl.Name = "lbl" + item.ToString();
                    lbl.Text = item.ToString() + ":";
                    lbl.AutoSize = true;
                    lbl.Location = new Point(10, 10 + i);
                    lbl.Size = new Size(50, 50);

                    var txtBox = new TextBox();
                    txtBox.Name = item.ToString();
                    txtBox.Location = new Point(150, 1 + i);
                    txtBox.Size = new Size(200, 20);
                    i += 30;

                    gbInfoBug.Size = new Size(500, 40 + i);
                    gbInfoBug.Controls.Add(lbl);
                    gbInfoBug.Controls.Add(txtBox);

                    gbButton.Location = new Point(160, 130 + i);

                    gbSearch.Location = new Point(120 + i, 80);
                    gbSearch.Size = new Size(600, 200);

                    gbDuplicate.Location = new Point(120 + i, 300);
                    gbDuplicate.Size = new Size(600, 200);

                    gbTemp.Location = new Point(120 + i, 500);
                    gbTemp.Size = new Size(600, 200);
                   
                }
            }
            catch { }
        }

        private List<string> GetFieldCheck(DataTable dtBuild)
        {
            List<string> listFieldChecked = new List<string>();// contains field chose.

            if (!string.IsNullOrEmpty(pub_str_FieldChecked))
            {
                listFieldChecked.Add(dtBuild.Columns[0].ToString());
                while (pub_str_FieldChecked != string.Empty)
                {
                    listFieldChecked.AddRange(pub_str_FieldChecked.Split('_'));
                    break;
                }
            }
            return listFieldChecked;
        }

        private void CheckDulicate(string str_bug, DataTable dtBuild, List<string> listFieldChecked)
        {
            threshold = double.Parse(txtthreshold.Text.ToString());
            dicbug_duplicate = new Dictionary<string, double>();
            dictemp_duplicate = new Dictionary<string, double>();
            Dictionary<string, double> bug_new = new Dictionary<string, double>();

            bug_new = cal.Create_Vecto(str_bug); //create vector for current bug
            
            // read BOW
            Dictionary<string, double> getBOW = new Dictionary<string, double>();
            getBOW = com.readBagOfWord();

            // read Frequency
            Dictionary<string, double> dicFre = new Dictionary<string, double>();
            dicFre = com.readFrequencyWord();

            // get empty columns list
            List<int> listColumns = new List<int>();
            listColumns = com.disField(dtBuild);

            double avg = cal.calculation_dl_avg(dtBuild, dicFre, listColumns);

            for (int i = 0; i < dtBuild.Rows.Count; i++)
            {
                string s = "";
                foreach (string t in listFieldChecked)
                {
                    s += dtBuild.Rows[i][t].ToString() + " ";
                }
                Dictionary<string, double> bug_old = new Dictionary<string, double>();
                bug_old = cal.Create_Vecto(s);

                double check = cal.Compare_Vecto(bug_new, bug_old); // compare new bug and old bug

                if (bug_new.Count >= avg && bug_old.Count >= avg)
                {
                    if (check >=threshold)
                    {
                        if (dicbug_duplicate.ContainsKey(s))
                            continue;
                        else
                            dicbug_duplicate.Add(s, check);
                    }
                }
                if (bug_new.Count < avg && bug_old.Count < avg)
                {
                    if (check >= threshold)
                    {
                        if (bug_new.Count == bug_old.Count)
                        {
                            if (dicbug_duplicate.ContainsKey(s))
                                continue;
                            else
                                dicbug_duplicate.Add(s, check);
                        }
                        else
                        {
                            if (dictemp_duplicate.ContainsKey(s))
                                continue;
                            else
                                dictemp_duplicate.Add(s, check);
                        }
                    }
                }
            }
        }

        private void ShowCboRow(DataTable dtBuild)
        {
            Dictionary<string, string> test = new Dictionary<string, string>();
            for (int i = 0; i < dtBuild.Rows.Count; i++)
            {
                test.Add(i.ToString(),i.ToString());
            }
            cboRow.DataSource = new BindingSource(test, null);
            cboRow.ValueMember = "Key";
            cboRow.DisplayMember = "Value";


        }

        #endregion
    }
}
